package util

import (
	"errors"
	"fmt"
	"github.com/google/uuid"
	"go-api-template/service"
	"math/rand"
	"os"
	"path/filepath"
	"strings"
	"time"
)

var (
	redis = service.Redis // 使用前配置设置: redis.enable: true
	log   = service.Log
)

// GetExecutePath 获取程序目录
func GetExecutePath() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		panic(err)
	}
	return dir
}

// GetCode 获取验证码
func GetCode(width int) string {
	numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(numeric)
	rand.Seed(time.Now().UnixNano())

	var sb strings.Builder
	for i := 0; i < width; i++ {
		fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
	}
	return sb.String()
}

func CheckCode(codeType string, event string, codeKey_ string, code string) (err error) {
	var codeResult string
	codeKey := fmt.Sprintf("%s.%s.%s", codeType, event, codeKey_)
	log.Debug(codeKey)
	switch codeType {
	case "mail":
		codeResult, err = redis.Get(codeKey).Result()
	}

	log.Debug(codeResult)
	log.Debug(code)
	if codeResult != code {
		return errors.New("Code check error")
	} else {
		redis.Del("mail." + codeKey)
	}

	return
}

// DeletePreAndSufSpace 删除左右两边空格
func DeletePreAndSufSpace(str string) string {
	strList := []byte(str)
	spaceCount, count := 0, len(strList)
	for i := 0; i <= len(strList)-1; i++ {
		if strList[i] == 32 {
			spaceCount++
		} else {
			break
		}
	}

	strList = strList[spaceCount:]
	spaceCount, count = 0, len(strList)
	for i := count - 1; i >= 0; i-- {
		if strList[i] == 32 {
			spaceCount++
		} else {
			break
		}
	}

	return string(strList[:count-spaceCount])
}

// GetRequestId 获取请求ID
func GetRequestId() string {
	return uuid.New().String()
}
